package com.sxj.corejava.code12_jdbc;

import com.sxj.corejava.util.DataAccessException;
import com.sxj.corejava.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 石小俊
 * @date 2024年07月03日 10:17
 */
public class Test10_事务操作 {

    public static void main(String[] args) throws SQLException {
        User user = new User("zhangsan", "777777", "13112365478", "安徽-六安");
        insertUser(user);
    }


    public static void insertUser(User user) throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = JDBCUtil.getConnection();
            // 开启事务
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            ps.executeUpdate();

            int i = 1 / 0;
            conn.commit();
        } catch (DataAccessException e) {
            e.printStackTrace();
            conn.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
        }
    }

}
